<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-view">
      <template #high_form="{ form }">
        <!-- {{highFieldList}} -->
        <!-- {{form}} -->
        <!-- {{originOption}} -->
        <XForm ref="form" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption" class="grid grid-cols-3"> </XForm>
      </template>
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption"> </XForm>
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="onAudit()">审核</VButton>
        <VButton type="primary" @click="addUpdate">变更</VButton>
        <VButton @click="onDelete()">
          <svg-icon icon-class="del_icon" class="mr-[2px] text-red"></svg-icon>
          删除
        </VButton>
      </template>
    </VTable>

    <!-- ASIN销量趋势 -->
    <AsinSalesTrend ref="AsinSalesTrendRef" />

    <!-- 库存信息 -->
    <InventoryDtl ref="InventoryDtlRef" />
    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" />
    <!-- 日志 -->
    <XLog ref="logRef" :api="planSpaLog"></XLog>
  </VPage>
</template>

<script setup lang="jsx">
import {
  planSpaList,
  planSpaReview,
  planSpaDelete,
  planSpaUpdateRemark,
  planSpaUpdateTransportationType,
  // planSpaUpdateStockinQuantity,
  planSpaUpdateShipTime,
  planSpaLog,
  purchaseDemandSkuDetail,
} from "@/api/plan"
import { ElMessage, ElMessageBox } from "element-plus"

import XForm from "@/components/XForm/index.vue"
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()

// ASIN销量趋势
import AsinSalesTrend from "@/views/plan/components/AsinSalesTrend/index.vue"
const AsinSalesTrendRef = ref()

// 库存信息
import InventoryDtl from "@/views/plan/stockUpFba/components/inventoryDtl.vue"
const InventoryDtlRef = ref()
// 表格操作
const handleFunction = ref({
  // 查看ASIN销量趋势
  openTendencyChart: (row) => {
    AsinSalesTrendRef.value.open(row.id)
  },
  // 修改运输类型
  updateTransportation: (row) => {
    planSpaUpdateTransportationType({
      id: row.id,
      transportation_type: row.transportation_type,
    }).then((res) => {
      ElMessage.success(res.message)
    })
  },
  // // 修改需求数量
  // updateQuantity: (row) => {
  //   console.log(123)
  //   console.log(row)

  //   if ("5,6".includes(row.review_status)) {
  //     ElMessage({ showClose: true, message: "此状态不可修改", type: "warning" })
  //     return
  //   }
  //   planSpaUpdateStockinQuantity({
  //     id: row.id,
  //     stocking_quantity: row.spa_analysis.stocking_quantity,
  //   }).then((res) => {
  //     ElMessage.success(res.message)
  //   })
  // },
  // 修改备注
  editRemark: (row) => {
    openConfirmInput("remark", row)
  },
  // 修改 预计发货时间
  shipTimeChange: (row) => {
    planSpaUpdateShipTime({ id: row.id, estimated_shipping_time: row.estimated_shipping_time }).then((res) => {
      ElMessage.success(res.message)
    })
  },
})

import { enumGet, enumOptions } from "@/api"
import { getEnum, getAloneEnum } from "@/utils/enumUtils"
import { getCountry, getSupplie } from "@/api"
import {
  originOption, // 枚举
  stockUpPlanColumns, // 备货计划明细 列
  handleFunctions, // 操作
  fieldList, // 搜索条件 配置
  highFieldList, // 高级搜索 配置
  currentConfirmOpt, // 表单编辑 弹窗配置
} from "./config.jsx"

import action from "@/utils/action.js"

const router = useRouter()
// 变更
const addUpdate = () => {
  // console.log(11223)
  let arr = getSelectRow()

  if (arr.length != 1) {
    ElMessage({ showClose: true, message: "只能选择一条数据", type: "warning" })
    return
  }
  if (arr?.[0].review_status != 6) {
    return ElMessage({ showClose: true, message: "已审核状态才可以变更", type: "warning" })
  }
  purchaseDemandSkuDetail({ source_id: arr[0]?.id }).then((res) => {
    sessionStorage.setItem("PURCHASE_HANDLE", JSON.stringify({ pds_id: res.data.pds_id, demand_no: res.data.demand_no, sku: res.data.sku, sku_no: res.data.sku_no }))
    action.setGlobalState({
      changeMicoTabsPath: {
        path: "/purchase/demand/sku",
        type: "push",
      },
    })
  })
}
onActivated(() => {
  setParams()
})
onMounted(() => {
  setParams()
  nextTick(() => {
    getOption()
    handleFunctions.value = { ...handleFunctions.value, ...handleFunction.value }
  })
})
const setParams = () => {
  nextTick(() => {}).then(() => {
    const { isParams, site_id, asin } = history.state || {}
    if (isParams) {
      let data = { skuRange: { type: "asin", value: asin }, asin, site_id: [site_id] }
      // https://www.tapd.cn/43903947/bugtrace/bugs/view/1143903947001008863
      data.is_created_po = false
      // console.log(data);
      tableRef?.value.setForm(data)
      query()
    }
  })
}

// 获取下拉数据
const getOption = async () => {
  let keys = [...fieldList.value, ...highFieldList.value].filter((v) => v.originField)
  let enumParams = keys.filter((v) => v.enumOriginField).map((v) => v.originField)
  const enumData = (await enumOptions({ params: enumParams }))?.data

  originOption.value.country = (await getCountry()).data
  let enumGetName = keys.filter((v) => !v.enumOriginField).map((v) => v.originField)
  enumGetName = [...enumGetName]

  const { data } = await enumGet({ name: [...enumGetName, "Plan.PlanSpaChange.ReviewStatusEnum"] })

  let optData = { ...enumData, ...data }
  for (const key in optData) {
    originOption.value[key] = optData[key]
  }
  // originOption.value.country = (await getCountry()).data
  originOption.value.amazonSite = (await getAloneEnum(["amazonSite"])).amazonSite
  originOption.value.supplier = (await getSupplie())?.data
}
const tableRef = ref()

const data = reactive({
  batchVisible: false,
  currentConfirm: {},
})
const { batchVisible, currentConfirm } = toRefs(data)

// 删除
const onDelete = (row = null) => {
  let arr = []
  if (row) {
    arr = [row]
  } else {
    arr = getSelectRow()
    // console.log(456)
    // console.log(arr)

    // console.log(arr)
    if (!arr.length) {
      return false
    }
  }
  // console.log(arr)
  ElMessageBox.confirm(`此操作将删除 ${arr.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      planSpaDelete({ id: arr.map((v) => v.id) }).then((res) => {
        ElMessage.success("操作成功")
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
// 审核
const onAudit = (row = null) => {
  let params = {
    ids: [],
  }
  let arr = []
  if (row) {
    params.ids = [row.id]
    params.review_status = row.review_status
  } else {
    let arr = getSelectRow()
    if (!arr.length) return
    let status = [...new Set(arr.map((v) => v.review_status))]
    if (status.length > 1) {
      return ElMessage({ showClose: true, message: "只能审核同一状态数据", type: "warning" })
    }
    if (!"1,2,3,4".includes(status[0])) {
      return ElMessage({ showClose: true, message: "单据不可审核", type: "warning" })
    }

    params.review_status = status[0]
    params.ids = arr.map((v) => v.id)
  }
  // console.log(params)
  openConfirmInput("audit", params)
}

// 开启 弹窗 表单编辑
const openConfirmInput = (type, param) => {
  let confirm = {}
  // console.log(param)
  switch (type) {
    case "audit": // 审核
      confirm = currentConfirmOpt.audit
      confirm.form = { id: param.ids }
      let confirmOriginOption = {
        review_type: originOption.value.review_type[param.review_status],
      }
      confirm.originOption = confirmOriginOption
      break
    case "remark": // 备注
      confirm = currentConfirmOpt.remark
      confirm.form = { id: param.id, remark: param.remark }
      break
  }

  // confirm.originOption = originOption.value
  confirm.type = type
  currentConfirm.value = confirm
  batchVisible.value = true
}
// 保存 弹窗 表单编辑
const handleConfirmSubmit = async (param) => {
  // console.log(param)
  let requests = null
  switch (currentConfirm.value.type) {
    case "audit": // 审核
      requests = planSpaReview
      break
    case "remark": // 备注
      requests = planSpaUpdateRemark
      break
  }
  requests(param).then((res) => {
    ElMessage.success(res.message)
    batchVisible.value = false
    query()
    nextTick(() => {
      currentConfirm.value = {}
    })
  })
}

const formOption = ref({
  inline: true,
})

// 计算行高
const rowStyle = ({ row, column }) => {
  return { height: `${row?.aaaaa?.length > 1 ? row?.aaaaa?.length * 80 : 116}px` }
}
// //列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      skuRange: { type: "sku", value: "" },
      timeRange: { type: "created_at", value: "", range: true },
    },
  },
  headerCellStyle: { height: "39px" },
  cellStyle: rowStyle,
  columns: [
    /* ----------------------- 分割 ----------------------- */
    // {
    //   title: "采购信息",
    //   width: 180,
    //   slots: {
    //     default: ({ row }) => (
    //       <div>
    //         {row.aaaaa.map((d) => (
    //           <div class="row-item">
    //             <VText title="购单号" value={d.xxx} line={1} />
    //             <span class="flex">
    //               <span class="flex-1">
    //                 <VText title="状态" value={d.xxx} />
    //               </span>
    //               <VText title="采购数量" value={d.xxx} />
    //             </span>
    //             <VText title="预计到货" value={d.xxx} />
    //           </div>
    //         ))}
    //       </div>
    //     ),
    //   },
    // },
    // {
    //   title: "外验单信息",
    //   width: 180,
    //   slots: {
    //     default: ({ row }) => (
    //       <div>
    //         {row.aaaaa.map((d) => (
    //           <div class="row-item">
    //             <VText title="外验单号" value={d.xxx} line={1} />
    //             <VText title="状态" value={d.xxx} />
    //             <VText title="预计验货时间" value={d.xxx} />
    //           </div>
    //         ))}
    //       </div>
    //     ),
    //   },
    // },
    // {
    //   title: "备库单信息",
    //   width: 180,
    //   slots: {
    //     default: ({ row }) => (
    //       <div>
    //         {row.aaaaa.map((d) => (
    //           <div class="row-item">
    //             <VText title="备货单号" value={d.xxx} line={1} />
    //             <span class="flex">
    //               <span class="flex-1">
    //                 <VText title="状态" value={d.xxx} />
    //               </span>
    //               <VText title="发货数量" value={d.xxx} />
    //             </span>
    //             <span class="flex">
    //               <span class="flex-1">
    //                 <VText title="预计发货" value={d.xxx} />
    //               </span>
    //               <VText title="物流商" value={d.xxx} />
    //             </span>
    //           </div>
    //         ))}
    //       </div>
    //     ),
    //   },
    // },
    // {
    //   title: "备注信息",
    //   width: 240,
    //   slots: {
    //     default: ({ row }) => (
    //       <div class="cursor-pointer text-[#3487ff] " onClick={() => editRemark(row)}>
    //         {row.remark || "-"}
    //       </div>
    //     ),
    //   },
    // },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    ajax: {
      query: ({ page, form }) => {
        // console.log(tableRef.value.getForm())
        let { is_created_po } = tableRef.value.getForm()
        let params = {
          ...initForm(form),
          page: page.pageNum,
          page_size: page.pageSize,
          is_created_po,
        }
        return planSpaList(params)
      },
    },
  },
})
const handleColumn = {
  title: "操作",
  width: 150,
  fixed: "right",
  slots: {
    default: ({ row }) => {
      return [
        <div>
          {row.review_status != 6 ? (
            <el-button link type="primary" onClick={() => onAudit(row)}>
              审核
            </el-button>
          ) : (
            ""
          )}

          <el-button link type="primary" onClick={() => logRef?.value.open({ spa_id: row.id })}>
            日志
          </el-button>
          <el-button link type="danger" onClick={() => onDelete(row)}>
            删除
          </el-button>
        </div>,
      ]
    },
  },
}
tableOptins.columns = [{ type: "checkbox", fixed: "left", width: 60 }, ...stockUpPlanColumns, handleColumn]
// tableOptins.columns.unshift(...stockUpPlanColumns)
// console.log(tableOptins.columns)

const initForm = (form) => {
  let keys = ["sku", "custom_sku", "asin"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  return form
}

// 获取已选中的行
const getSelectRow = () => {
  const arr = tableRef?.value.$table.getCheckboxRecords()
  if (!arr.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  return arr
}

// 查询
const query = () => {
  tableRef?.value.query()
}
</script>
<style lang="scss" scoped>
:deep(.row-item) {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px;
  margin-bottom: 2px;
}
.table-view {
  :deep(.vxe-cell) {
    max-height: 100% !important;
  }
  :deep(.status-tag) {
    padding: 0 4px;
    height: 14px;
    line-height: 14px;
    text-align: center;
    border-radius: 2px;
    font-size: 10px;
  }
  :deep(.date-picker) {
    width: 110px;
    .el-input__prefix-inner {
      display: none;
    }
  }
}
</style>
